/**
 * Lockbox
 * a Password and Secret Information Manager
 * View to display a table of LockboxItems
 *
 * Created by Nathan Black
 * 
 * Licensed under GPL v2
 */

#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UIKit/UISegmentedControl.h>
#import <UIKit/UIAlertSheet.h>
#import "LockboxListView.h"
#import "LockboxTableCell.h"
#import "LockboxOptions.h"


@interface LockboxListView (Private)

- (void)transToItemView:(LockboxItem*)item cell:(LockboxTableCell*)cell;
- (void)transToOptionsView;
- (void)updateDisplayItems;

@end

@implementation LockboxListView

//////////// Table Data /////////////////
- (int) numberOfRowsInTable: (UITable *)table
{
    return [_displayItems count];
}

- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col
{
    if (row < 0 || row >= [_displayItems count]) return NULL;
    //NSLog(@"cellForRow: %d", row);
   
    LockboxTableCell* cell = [[[LockboxTableCell alloc] init] autorelease];
    [cell setDelegate:_cellDelegate];
    [cell setItem:[_displayItems objectAtIndex:row]];
    
    // Can insert or remove controls work in a non-Preferences Table? it seems not.
     /*if (row == 2) {
        id removeCtl = [cell createRemoveControl];
        NSLog(@"removeCtl: %@", removeCtl);
        //[cell removeControlWillShowRemoveConfirmation:removeCtl];
        [cell addSubview:removeCtl];
        //[cell removeControl:removeCtl willRemoveTarget:cell];	// IMP=0x323ea27c
        NSLog(@"queiried removeControl: %@", [cell removeControl]);
        NSLog(@"isRemoveButtonVisible: %d", [removeCtl isRemoveButtonVisible]);
        [cell setShowDisclosure:FALSE];
        [removeCtl showRemoveButton:YES animated:YES];
    }*/
    return cell;
}


- (void)dealloc
{
    [_table release];

	[super dealloc];
}

///////////// Constructor ////////////////
- (id)initWithFrame:(struct CGRect)frame app:(id)app
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _storage = [LockboxStorage globalInstance];
        _cellDelegate = app;
        
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        
        CGRect navBarRect = frame;
        frame.origin.y += LBLV_NAVBAR_HEIGHT;
        frame.size.height -= LBLV_NAVBAR_HEIGHT;
        _table = [[UITable alloc] initWithFrame:frame];
        [_table setRowHeight:LTC_ROWHEIGHT];  

        navBarRect.size.height = LBLV_NAVBAR_HEIGHT;
        _navBar = [[UINavigationBar alloc] initWithFrame: navBarRect];
        [_navBar showButtonsWithLeftTitle: @"Options" rightTitle:@"New" leftBack: FALSE];
        [_navBar setBarStyle: 3];
        [_navBar enableAnimation];
        [_navBar setDelegate: self];

        _filterLabel = [[UINavigationItem alloc] initWithTitle:@"All"];
        [_navBar pushNavigationItem:_filterLabel];

        UITableColumn *col = [[UITableColumn alloc] initWithTitle: @"Lockbox Items"
            identifier: @"itemCol" width: frame.size.width];
        [_table addTableColumn: col];
        [_table setSeparatorStyle: 1];

        [_table setDataSource: self];
        [_table setDelegate: self];
        
        [self updateDisplayItems];
        
        [self addSubview:_navBar];
        [self addSubview:_table];
        [_table reloadData];
        
        CFRelease(colorSpace);
    }
    
    return self;
}

- (void)refresh
{
    [self updateDisplayItems];
    [_table reloadData];
}

- (void)filtersUpdated
{
    [self refresh];
}

- (void)updateDisplayItems
{
    [_displayItems release];
    _displayItems = [[NSMutableArray alloc] init];
    
    LockboxOptions* opts = [LockboxOptions globalInstance];
    if ([opts tagFilterOn]) {
        NSLog(@"Filter is on, updating.");
        
        LockboxItem *item;
        NSString *tag, *filterTag;
        NSEnumerator *itemEnum = [[_storage items] objectEnumerator];
        while ((item = [itemEnum nextObject])) {
            NSEnumerator *itemTagEnum = [item->tags objectEnumerator];
            BOOL bAdded = false;
            while ((tag = [itemTagEnum nextObject])) {
                NSEnumerator *filterTagEnum = [[opts tagFilters] objectEnumerator];
                while ((filterTag = [filterTagEnum nextObject])) {
                    if ([filterTag caseInsensitiveCompare:tag] == NSOrderedSame) {
                        [_displayItems addObject:item];
                        NSLog(@"Added item with key: %@", item->key);
                        bAdded = true;
                        break;
                    }
                }
                if (bAdded) break;
            }
        }

        NSMutableString* filterList = [[[NSMutableString alloc] init] autorelease];
        NSEnumerator *filterTagEnum = [[opts tagFilters] objectEnumerator];
        while ((filterTag = [filterTagEnum nextObject])) {
            if ([filterList length] > 0) {
                [filterList appendString:@", "];
            }
            [filterList appendString:filterTag];
        }
        [_filterLabel setTitle:filterList];
    }
    else {
        NSLog(@"Filter is off, using a copy");
        [_displayItems addObjectsFromArray:[_storage items]];
        [_filterLabel setTitle:@"All"];
        //NSLog(@"items count: %d copy count: %d", [[_storage items] count], [_displayItems count]);
    }
}

- (BOOL)canDeleteRow:(int)row
{
    return YES;
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button
{
    [sheet dismiss];
}

- (void)navigationBar:(UINavigationBar*)navbar buttonClicked:(int)button
{
    NSLog(@"navBar buttonClicked: %d", button);
    @try {
        switch (button) {
            case 1: // Filters
            {
                NSLog(@"Saving user data...");
                [_storage save];
                NSLog(@"Done");
                
                [_table selectRow:-1 byExtendingSelection:FALSE];
                if (_cellDelegate != nil && [_cellDelegate respondsToSelector:@selector(transToOptionsView)])
                {
                    [_cellDelegate transToOptionsView];
                }
                break;
            }
            
            case 0: // New
                if (_cellDelegate != nil && [_cellDelegate respondsToSelector:@selector(transToItemView:cell:)])
                {
                    [_cellDelegate transToItemView:NULL cell:NULL];
                }
                break;
        }
    }
    @catch (NSException* ex) {
        NSLog(@"***Caught exception during save: %@ reason: %@", [ex name], [ex reason]);
    }
}

/*- (void)tableRowSelected:(NSNotification *)notification
{
    
}

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
     NSLog(@"LBListView: Requested method for selector: %@", NSStringFromSelector(selector));
     return [super methodSignatureForSelector:selector];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    NSLog(@"LBListView: Request for selector: %@", NSStringFromSelector(aSelector));
    return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
     NSLog(@"LBListView: Called from: %@", NSStringFromSelector([anInvocation selector]));
    [super forwardInvocation:anInvocation];
}*/

@end
